<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <title>图片选择</title>
    <link rel="stylesheet" href="/admin/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/admin/layuiadmin/style/admin.css" media="all">
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        html {
            background-color: #fff !important;
        }

        .container {
            padding: 0 15px;
            width: 100%;
            min-height: 150px;
            box-sizing: border-box;
        }

        .tool-bar {
            width: 100%;
            box-sizing: border-box;
            padding-top: 20px;
        }

        .img-container {
            width: 100%;
            height: auto;
            box-sizing: border-box;
            display: flex;
            flex-wrap: wrap;
            justify-content: space-evenly;
            gap: 20px;
            padding: 5px 0;
            border: 2px dashed #ddd;
        }

        .img-item {
            width: 120px;
            height: 120px;
            box-sizing: border-box;
            padding: 10px;
            position: relative;
            border-radius: 10px;
        }

        .img-item img {
            width: 100%;
            height: 100%;
            cursor: pointer;
            border: 1px solid #eee;
        }

        .img-item .tool {
            position: absolute;
            top: 20px;
            right: 20px;
            box-sizing: border-box;
            padding: 3px 10px 0 10px;
            gap: 5px;
            background-color: rgba(0, 0, 0, .2);
            border-radius: 5px;
            display: none;
        }

        .img-item .tool i {
            color: #fff;
            cursor: pointer;
        }

        .active {
            background-color: #00ff80;
        }

        .null {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 40px;
            color: #444;
        }

        .img-big {
            width: auto;
            height: 80vh;
        }

        .page {
            width: 100%;
            text-align: center;
        }
        .id{
            top: 20px;
            left: 20px;
            position: absolute;
            color: #ff4c23;
            font-weight: bold;
            font-size: 25px;
        }
        .panel{
            height: 36px;
            width: auto;
            float: right;
            border: 1px dashed #ddd;
            display: flex;
            justify-content: center;
            align-items: center;
            box-sizing: border-box;
            padding: 0 15px;
        }
        .panel::before{
            content: '已选择:';
            color: #bbb;
            margin-left: -75px;
            padding-right: 20px;
        }
        .spi{
            color: #00B7ED;
            margin: 0 3px;
        }
        .blue{
            color: #00B7ED;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="tool-bar layui-btn-container">
        <button class="layui-btn" id="upload"><i class="layui-icon layui-icon-upload"></i>上传本地</button>
        <button class="layui-btn layui-btn-warm" id="upload_cloud"><i class="layui-icon layui-icon-upload"></i>上传云端
        </button>
        <!-- <button class="layui-btn layui-btn-checked layui-btn-disabled" id="download" disabled><i class="layui-icon layui-icon-download-circle"></i>下载
        </button> -->
        <button class="layui-btn layui-btn-danger layui-btn-disabled" id="delete" disabled><i class="layui-icon layui-icon-delete"></i>删除</button>
        <button class="layui-btn" id="flash"><i class="layui-icon layui-icon-refresh"></i>刷新</button>
        <button class="layui-btn" id="select_all">全选</button>
        <button class="layui-btn" id="select_reserve">反选</button>
        <button class="layui-btn" id="select_none">全不选</button>
        <div class="panel" id="panel"></div>
    </div>
    <div class="img-container" id="img-container">
        <div class="null">没有图片</div>
    </div>

</div>


<!--  选择的图片的值都会存储在这个input里，它的值为JSON字符:{path:'图片写入路径',list:['图片显示路径']}  -->
<input type="hidden" name="path" id="path" value='{"path":"","list":[]}'/>



<div class="page">
    <div id="page"></div>
</div>
</body>
</html>

<script type="text/html" id="tpl">
    {{#  layui.each(d, function(index, item){ }}
    <div class="img-item" id="img_{{= item.id}}">
        <div class="id {{= item.site?'blue':'' }}">{{= item.id}}</div>
        <div class="tool">
            <i class="layui-icon layui-icon-search" onclick="show('{{= JSON.stringify(item) }}')"></i>
            <i class="layui-icon layui-icon-about" onclick="detail('{{= JSON.stringify(item) }}')"></i>
            <!-- <i class="layui-icon layui-icon-download-circle" onclick="download_img('{{= JSON.stringify(item) }}')"></i> -->
            <i class="layui-icon layui-icon-delete" onclick="delete_img('{{= JSON.stringify(item) }}')"></i>
        </div>
        <img src="{{= item.src }}" alt="图片" onclick="select('{{= JSON.stringify(item) }}')">
    </div>
    {{#  }) }}
</script>

<script src="/admin/layuiadmin/layui/layui.js"></script>
<script>
    // 初始化
    const {parent} = window
    var $ = layui.$
    var layer = layui.layer
    var tpl = layui.laytpl
    var page = layui.laypage
    var upload = layui.upload
    var self = this
    var data = {
        list: [], // 图片总列表
        selectedList: {}, // 选中的图片列表
        count: 0, // 总条数
    }

    // 响应式代理
    let temp = data.selectedList
    Object.defineProperty(data, 'selectedList', {
        configurable: true,
        enumerable: true,
        get() {
            return temp
        },
        set(v) {
            temp = v
            let arr = []
            let arr2 = []
            let arr3 = []
            for (let i in v) {
                arr.push(v[i].path)
                arr2.push(v[i].src)
                arr3.push(v[i].id)
            }
            const res = {
                path: arr.join(','),
                list: arr2
            }
            if (arr3.length){
                $('#panel').html(arr3.join(`<span class="spi">---</span>`))
                $('#panel').show(100)
                $("#delete").removeAttr('disabled').removeClass('layui-btn-disabled')
                $("#download").removeAttr('disabled').removeClass('layui-btn-disabled')
            }else{
                $('#panel').hide(100)
                $("#delete").attr('disabled','').addClass('layui-btn-disabled')
                $("#download").attr('disabled','').addClass('layui-btn-disabled')
            }
            $("#path").val(JSON.stringify(res))
            console.log(`Select->Change`, res)
            active()
            return v
        }
    })

    // 响应式代理
    let temp2 = data.count
    Object.defineProperty(data, 'count', {
        configurable: true,
        enumerable: true,
        get() {
            return temp2
        },
        set(v) {
            temp2 = v
            return v
        }
    })

    // 模板渲染
    function render() {
        let source = data.list
        if (source.length) {
            tpl($('#tpl').html()).render(source, function (str) {
                $('#img-container').html(str)
            })
        } else {
            $('#img-container').html(`<div class="null">没有图片</div>`)
        }
        // 图片工具栏的显示效果
        $(".img-item").mouseenter(function () {
            $(this).children('.tool').show(100)
        }).mouseleave(function () {
            $(this).children('.tool').hide(100)
        });
        active()
    }

    // 异步刷新
    async function init(args = {}) {
        layer.load(2)
        return await $.ajax({
            url: '/admin/index/select_img',
            method: 'POST',
            data: {...args},
            success(e) {
                data.list = format(e.data)
                data.count = e.count
                layer.closeAll('loading')
                render()
                return Promise.resolve(e)
            },
            fail(e) {
                layer.closeAll('loading')
                return Promise.reject(e)
            }
        })
    }

    // 同步刷新
    function init_sync(args = {}) {
        layer.load(2)
        var res = []
        $.ajax({
            url: '/admin/Tools/select_img',
            method: 'POST',
            async: false,
            data: {...args},
            success(e) {
                data.list = format(e.data)
                data.count = e.count
                layer.closeAll('loading')
                render()
                res = e
            },
            fail(e) {
                layer.closeAll('loading')
                res = e
            }
        })
        return res
    }

    function format(e) {
        return e.map(i => {
            i['src'] = i['path']
            if (i['site']) i['src'] = i['site'] + i['path']
            return i
        })
    }

    // 选择图片事件
    function select(obj) {
        obj = JSON.parse(obj)
        let id = `img_${obj.id}`
        let arr = data.selectedList

        // 多选
        if (!arr[id]) {
            // data.selectedList = {} // 加上这句变单选
            arr[id] = obj
        } else {
            delete arr[id]
        }
        data.selectedList = arr
    }

    // 刷新选中样式
    function active() {
        $('.img-item').each(function () {
            $(this).removeClass('active')
        })
        for (i in data.selectedList) {
            $(`#${i}`).addClass('active')
        }
    }

    // 预览图片
    function show(obj) {
        obj = JSON.parse(obj)
        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            shadeClose: true,
            offset: 'auto',
            area: ['auto', 'auto'],
            content: `<img src="${obj.src}" class="img-big">`,
        });
    }

    // 单个下载
    function download_img(obj) {
        // TODO 实现下载
        obj = JSON.parse(obj)
        layer.msg('下载')
    }

    // 图片信息
    function detail(obj) {
        // TODO 实现图片信息
        obj = JSON.parse(obj)
        layer.msg('图片信息')
    }

    // 单个删除
    function delete_img(obj) {
        obj = JSON.parse(obj)
        layer.confirm(`确认要删除<span class="layui-font-purple">${obj.site?'云端':'本地'}</span>图片 ${obj.id},项目中如有用到该图片的地方将无法显示，请谨慎操作！`,{icon:3,title:"确认删除"},function (){
            handle_delete_img({
                id:obj.id
            })
        })
    }

    // 分页组件
    function page_render() {
        page.render({
            elem: 'page',
            count: data.count,
            layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'],
            jump: function (obj, index) {
                if (index) return
                this.count = init_sync({
                    page: obj.curr,
                    limit: obj.limit
                }).count
            }
        })
    }

    init_sync() // 获取数据
    page_render() // 渲染分页
    $('#panel').hide() // 隐藏选择指示器

    // 异步删除方法
    function handle_delete_img(args){
        $.ajax({
            url:'/admin/Tools/select_img',
            method:"POST",
            data:{...args,action:'delete'},
            success(e){
                if (e.code === 200){
                    layer.msg('删除成功')
                }
                init_sync()
                page_render()
            },
            error(e){
                layer.msg('删除失败')
                console.log(e)
            }
        })
    }

    // 同步删除方法
    function handle_delete_img_sync(args){
        $.ajax({
            url:'/admin/Tools/select_img',
            method:"POST",
            data:{...args,action:'delete'},
            async:false,
            success(e){
                if (e.code === 200){
                    layer.msg('删除成功')
                }
                init_sync()
                page_render()
            },
            error(e){
                layer.msg('删除失败')
                console.log(e)
            }
        })
    }

    // 异步删除方法
    function handle_download_img(args){
        $.ajax({
            url:'/admin/Tools/select_img',
            method:"POST",
            data:{...args,action:'download'},
            success(e){
                if (e.code === 200){
                    layer.msg('下载已开始')
                }
            },
            error(e){
                layer.msg('下载失败')
                console.log(e)
            }
        })
    }

    // 上传本地
    upload.render({
        elem: '#upload' //绑定元素
        , url: "/admin/Tools/upload?site=0&new=1" //上传接口
        , accept: 'file'
        , multiple: true
        , before() {
            parent.layer.load(2)
        }
        , done: function (res) {
            if (res.code === 0) {
                init_sync()
                page_render()
                layer.msg("上传成功");
            } else {
                layer.msg(res.msg);
            }
            parent.layer.closeAll('loading')
        }
        , error(e) {
            console.log(e)
            parent.layer.closeAll('loading')
        }
    });

    // 上传云端
    upload.render({
        elem: '#upload_cloud' //绑定元素
        , url: "/admin/Tools/upload?site=1&new=1" //上传接口
        , accept: 'file'
        , multiple: true
        , before() {
            parent.layer.load(2)
        }
        , done: function (res) {
            if (res.code === 0) {
                init_sync()
                page_render()
                layer.msg("上传成功");
            } else {
                layer.msg(res.msg);
            }
            parent.layer.closeAll('loading')
        }
        , error(e) {
            console.log(e)
            parent.layer.closeAll('loading')
        }
    });

    // 批量下载
    $('#download').click(function () {
        // TODO 实现下载
        layer.msg('批量下载：还没实现')
    })

    // 批量删除
    $('#delete').click(function () {
        layer.confirm(`确认要删除这些图片,项目中如有用到该图片的地方将无法显示，请谨慎操作！`,{icon:3,title:"确认删除"},function (){
            let id = []
            for (let i in data.selectedList){
                id.push(data.selectedList[i].id)
            }
            handle_delete_img({id})
        })
    })

    // 刷新
    $('#flash').click(function () {
        init_sync()
        page_render()
    })

    // 全选
    $('#select_all').click(function () {
        let arr = {}
        data.list.forEach(e => {
            let id = `img_${e.id}`
            arr[id] = e
        })
        data.selectedList = arr
    })

    // 反选
    $('#select_reserve').click(function () {
        let arr = {}
        data.list.forEach(e => {
            let id = `img_${e.id}`
            if (!data.selectedList[id]) {
                arr[id] = e
            }
        })
        data.selectedList = arr
    })

    // 全不选
    $('#select_none').click(function () {
        data.selectedList = {}
    })

    layui.config({
        base: '/admin/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'form'], function(){

    })
</script>
